const db = uniCloud.database();
function beforeRegister({
	userRecord,
	clientInfo
} = {}) {

	if (!userRecord.nickname) {
		console.log(".............nickname.................", userRecord.nickname);
		userRecord.nickname = "匿名" + Math.random().toString(36).substring(3, 9);
	}else{
		console.log(">>>>>>>>>>>>>nickname.................", userRecord.nickname);
	}

	// if (clientInfo.appId === '__UNI_123123') {
	// 	if (userRecord.role) {
	// 		userRecord.role.push('teacher')
	// 	} else {
	// 		userRecord.role = ['teacher']
	// 	}
	// }
	return userRecord // 务必返回处理后的userRecord
}

/**
 * 
 * 自定义回调钩子，修改uni-id-pages的源码，修改位置：uni-id-co/lib/utils/register.js
 * 
 * @param {Object} registerRes 注册用户返回结果
 */
async function afterRegister(registerRes){
	let errCode = registerRes.errCode;
	if(!errCode){
		let uid = registerRes.uid;
		let userRes = await db.collection("uni-id-users").doc(uid).get();
		let user = userRes.data && userRes.data[0]; 
		if (!user) {
		  console.error("用户不存在，uid=", uid);
		  return;
		}
		let res = await db.collection("accompany-user").add({
			uni_uid: uid,
			nickname: user.nickname
		});
		return res;
	}
}

module.exports = {
	beforeRegister,
	afterRegister
}